﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCA.Community.DAL.Model;
using LCA.Community.DAL.Interfaces;

namespace LCA.Community.DAL
{
    /// <summary>
    /// The repository for answers data manipulation.
    /// </summary>
    public class AnswersVotesRepository : BaseRepository<AnswerVote>, IAnswersVotesRepository
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AnswersVotesRepository"/> class.
        /// </summary>
        /// <param name="dataServiceContext">The data service context.</param>
        public AnswersVotesRepository(IDataServiceContext<AnswerVote> dataServiceContext)
            :base(dataServiceContext)
        {

        }

        /// <summary>
        /// Gets the answer votes by answer.
        /// </summary>
        /// <param name="answerID">The answer ID.</param>
        /// <returns>The votes of a answer</returns>
        public List<AnswerVote> GetAnswerVotesByAnswer(string answerID)
        {
            return (from vote in Entities
                    where vote.Post == answerID
                    select vote).ToList();
        }

        /// <summary>
        /// Deletes all answer votes.
        /// </summary>
        /// <param name="answerID">The answer ID.</param>
        public void DeleteAllAnswerVotes(string answerID)
        {
            var votes = GetAnswerVotesByAnswer(answerID).ToList();

            votes.ForEach(vote => Delete(vote));
        }

        /// <summary>
        /// Gets the answer votes by user.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <returns></returns>
        public List<AnswerVote> GetAnswerVotesByUser(string userID)
        {
            return (from vote in Entities
                    where vote.Author == userID
                    select vote).ToList();
        }

        /// <summary>
        /// Deletes all user votes.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        public void DeleteAllUserVotes(string userID)
        {
            var votes = GetAnswerVotesByUser(userID);

            votes.ForEach(vote => Delete(vote));
        }


        /// <summary>
        /// Determines whether a user has voted an answer.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <param name="answerID">The answer ID.</param>
        /// <returns>
        ///   <c>true</c> if user has voted the answer; otherwise, <c>false</c>.
        /// </returns>
        public bool HasUserVoted(string userID, string answerID)
        {
            var vote = Entities.Where(v => v.Author == userID && v.Post == answerID).FirstOrDefault();

            return vote != null;
        }
    }
}
